// pages/pet-detail/pet-detail.js
const { get } = require('../../utils/request')
const { getImageUrl, formatDate, showError, checkLogin } = require('../../utils/util')

Page({
  data: {
    petId: null,
    petInfo: {},
    imageList: [],
    createTime: '',
    loading: true,
    error: false,
    errorMsg: ''
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        petId: options.id
      })
      this.loadPetDetail()
    } else {
      this.setData({
        error: true,
        errorMsg: '参数错误',
        loading: false
      })
    }
  },

  onShareAppMessage() {
    return {
      title: `${this.data.petInfo.name} - 等待领养`,
      path: `/pages/pet-detail/pet-detail?id=${this.data.petId}`,
      imageUrl: this.data.imageList[0] || '/images/default-pet.png'
    }
  },

  // 加载宠物详情
  loadPetDetail() {
    this.setData({ 
      loading: true, 
      error: false 
    })

    get(`/pet/${this.data.petId}`).then(res => {
      const petInfo = res.data
      
      // 处理图片
      let imageList = ['/images/default-pet.png']
      if (petInfo.images) {
        const images = petInfo.images.split(',').filter(img => img.trim())
        if (images.length > 0) {
          imageList = images.map(img => getImageUrl(img.trim()))
        }
      }

      // 格式化创建时间
      const createTime = formatDate(petInfo.createTime)

      this.setData({
        petInfo,
        imageList,
        createTime,
        loading: false
      })

      // 设置页面标题
      wx.setNavigationBarTitle({
        title: petInfo.name || '宠物详情'
      })

    }).catch(err => {
      this.setData({
        error: true,
        errorMsg: '加载失败，请重试',
        loading: false
      })
    })
  },

  // 申请领养
  onAdopt() {
    if (!checkLogin()) {
      return
    }

    if (this.data.petInfo.status !== '待领养') {
      showError('该宠物已被领养')
      return
    }

    wx.navigateTo({
      url: `/pages/adoption/adoption?petId=${this.data.petId}&petName=${this.data.petInfo.name}`
    })
  },

  // 分享
  onShare() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  }
})
